$(document).ready( function() {

PlatformaWP = (function() {
	var MSG = {
		input : "<h3>Podaj kod aktywacyjny</h3><p>Kod: <input type='password' name='p_wp_activation_key' id='pwp_key' /></p>",
		success: "<p>Plugin Platforma Wordpress został poprawnie zainstalowany.</p>",
		failure: "<h3>Nieprawidlowy kod aktywacyjny</h3><p>Podaj ponownie kod aktywacyjny</p><p>Kod: <input type='password' name='p_wp_activation_key' id='pwp_key' /></p>"
	};
	var MSG_DIV = {
		target: "wpfooter",
		input: "pwp_key_input",
		success: 'pwp_key_success',
		failure: 'pwp_key_failure'
	};
	var executeServerAction = function(context, onSuccessFn) {
		jQuery.post(ajaxurl,
			context,
			function(response) {
				onSuccessFn($.parseJSON(response));
		    	}
		);
	};
	var showSuccessWindow = function () {
		$("<div id='" + MSG_DIV.success +"'></div>").appendTo('#' + MSG_DIV.target);
		var window = $('#' + MSG_DIV.success);
		window.append(MSG.success);
			window.dialog({
				title: 'Platforma Wordpress Instalacja ...',
				buttons: [{
					text: 'OK',
					click: function() {
						window.dialog('close');
						window.remove();
					}
				}]
			});
		
	};
	var showFailureWindow = function () {
		$("<div id='" + MSG_DIV.failure +"'></div>").appendTo('#' + MSG_DIV.target);
		var window = $('#' + MSG_DIV.failure);
		window.append(MSG.failure);
			window.dialog({
				title: 'Platforma Wordpress Błąd !',
				buttons: [{
					text: 'OK',
					click: function() {
						executeServerAction({'action': 'registerSite', 'key': $('#pwp_key').val()},
							 function(response) {
								window.dialog('close');
							 	window.remove();
								if (response.data === 'success') {
									showSuccessWindow();
									return;
								}
								showFailureWindow();
							}
						);
					}
				}]
			});
		
	};
	return {
		showInstallationWindow: function() {
			$("<div id='" + MSG_DIV.input +"'></div>").appendTo('#' + MSG_DIV.target);
			var window = $('#' + MSG_DIV.input);
			
			window.append(MSG.input);
			window.dialog({
				title: 'Platforma Wordpress Instalacja ...',
				buttons: [{
					text: 'Zapisz',
					click: function() {
						executeServerAction({'action': 'registerSite', 'key': $('#pwp_key').val()},
							 function(response) {
								window.dialog('close');
							 	window.remove();
								if (response.data === 'success') {
									showSuccessWindow();
									return;
								}
								showFailureWindow();
							}
						);
					}
				}, {
					text: 'Anuluj',
					click: function() {
						window.dialog('close');
					}
				}]
			});
		}
	}
})();

jQuery.post(ajaxurl, {'action': 'registerSite'},
	function(response) {
		if ($.parseJSON(response).data === 'false') {
			PlatformaWP.showInstallationWindow();
		}
	}
);

});

